#include "util.hpp"
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <functional>
#include <vector>
#define N 1024

using fun_t = std::function<void()>;

void INIT(std::vector<fun_t> &a)
{
    a.push_back(print);
    a.push_back(readbook);
    a.push_back(eat);
    a.push_back(seesea);
}

void EXEC_OTHRE(std::vector<fun_t> &a)
{
    for (auto const &x : a)
        x();
}
int main()
{
    setNonBlock(0);
    std::vector<fun_t> cbs;
    INIT(cbs);
    char buffer[N];
    while (1)
    {
        // printf(">>>>");
        // fflush(stdout);
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            if (errno == EAGAIN)
            {
                std::cout << "我没错,只是没数据" << std::endl;
                EXEC_OTHRE(cbs);
            }
            else if (errno == EINTR)
                continue; 
            else
            {
                std::cout << strerror(errno) << std::endl;
                break;
            }
        }
        sleep(1);
    }
    return 0;
}